package com.fjec.devops.schedule.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.DateUtil;
import com.fjec.devops.entity.StatOrderInfo;
import com.fjec.devops.feign.MarketClient;
import com.fjec.devops.service.IStatOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class StatOrderHandler extends BaseScheduleHandler {

    @Resource
    private MarketClient marketClient;

    @Resource
    private IStatOrderInfoService statOrderInfoService;

    public String handle(int days) {
        int num = 0;
        String result;
        try {
            num = this.handleSubOrderData(days);
            result = String.format("Handle subOrder number: [%d]", num);
        } catch (Exception ex) {
            result = String.format("Handle subOrder error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        return result;
    }

    private int handleSubOrderData(int days) {
        List<Map<String, Object>> resultMapList = marketClient.statSubOrderNumData(days);
        int num = 0;
        for (Map<String, Object> resultMap : resultMapList) {
            Integer orderType = MapUtils.getInteger(resultMap, "OrderType");
            String strStatDate = MapUtils.getString(resultMap, "StatDate");
            Integer orderNum = MapUtils.getInteger(resultMap, "Num");
            Long amount = MapUtils.getLong(resultMap, "Amount");
            LocalDate statDate = DateUtil.parseLd(strStatDate, "yyyy-MM-dd");
            QueryWrapper<StatOrderInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("StatDate", statDate)
                    .eq("OrderType", orderType);
            StatOrderInfo entity = statOrderInfoService.getOne(queryWrapper);
            if (entity == null) {
                entity = new StatOrderInfo();
                entity.setOrderType(orderType);
                entity.setStatDate(statDate);
                entity.setOrderNum(orderNum);
                entity.setOrderAmount(amount);
                entity.setCreateTime(DateUtil.nowLdt());
            } else {
                entity.setOrderNum(orderNum);
                entity.setOrderAmount(amount);
                entity.setUpdateTime(DateUtil.nowLdt());
            }
            statOrderInfoService.saveOrUpdate(entity);
            num++;
        }
        return num;
    }
}
